package com.shen.thread.state;
//测试生产者消费者》利用缓冲区解决：管程法

//生产者，消费者，产品，缓冲区
public class TestPc {
    public static void main(String[] args) {
        SynContainer container = new SynContainer();
        new Producer(container).start();
        new Consumer(container).start();
    }
}

class Producer extends Thread {
    SynContainer synContainer;

    public Producer(SynContainer synContainer) {
        this.synContainer = synContainer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {

            synContainer.push(new Ji(i));
            System.out.println("生产机>" + i);
        }
    }
}

class Consumer extends Thread {
    SynContainer synContainer;

    public Consumer(SynContainer synContainer) {
        this.synContainer = synContainer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("取走机>" + synContainer.pop().id);
        }
    }
}

//产品
class Ji {
    int id;

    public Ji(int id) {
        this.id = id;
    }
}

//缓冲区
class SynContainer {
    //容器大小
    Ji[] jis = new Ji[10];

    //容器计数器
    int count = 0;

    //生产者放入产品
    public synchronized void push(Ji ji) {
        //满了就等待
        if (count == jis.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        //没满就放入产品
        jis[count] = ji;
        count++;
        //通知消费者
        this.notifyAll();
    }

    //消费者消费产品
    public synchronized Ji pop() {
        //判断能否消费
        if (count == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果可以消费
        count--;
        Ji ji = jis[count];
        //通知生产者
        this.notifyAll();
        return ji;
    }
}